<template>
  <div class="color-picker">
    <div class="picker-card">
      <div class="picker-card--item" @click="toCopy(hexColor)">
        <el-text tag="p">16进制色值--点击复制</el-text>
        <el-text tag="p">{{hexColor}}</el-text>
        <div class="picker-card--item_tag water"></div>
      </div>
      <div class="picker-card--item ">
        <el-text tag="p">RGBA色值--点击复制</el-text>
        <el-text tag="p">{{rgbaColor}}</el-text>
        <div class="picker-card--item_tag water rgba" @click="toCopy(rgbaColor)"></div>
      </div>
    </div>
    <div class="picker-btn water" @click="onDraw">
      <el-icon :size="20">
        <MagicStick/>
      </el-icon>
      <span style="margin-left: 10px">魔法放大镜</span>
    </div>
  </div>
</template>
<script lang="ts">
import {ElMessage} from 'element-plus'
import {ref} from 'vue';
import { copy } from '@/utils/tools'

export default {
  name: 'ColorPicker',
  setup() {
    /* utils */
    const hex2rgba = (hex: string, opacity: string | number) => {
      return 'rgba(' + parseInt('0x' + hex.slice(1, 3)) + ',' + parseInt('0x' + hex.slice(3, 5)) + ','
          + parseInt('0x' + hex.slice(5, 7)) + ',' + opacity + ')';
    }
    if (!('EyeDropper' in window)) {
      ElMessage.warning('当前浏览器不支持！')
      return
    }
    /* 取色版逻辑 */
    const hexColor = ref('#ccc')
    const rgbaColor = ref('#ccc')
    const Dropper = new window.EyeDropper()
    const onDraw = async () => {
      try {
        const res = await Dropper.open()
        hexColor.value = res.sRGBHex
        rgbaColor.value = hex2rgba(res.sRGBHex, 1)
      } catch (e) {
        console.log('取消了')
      }
    }
    /* 复制 */
    const toCopy = (color: any) => {
      copy(color, '色值已复制到剪切板~')
    }
    return {onDraw, hexColor, rgbaColor, toCopy}
  }
}
</script>
<style lang="scss">
.color-picker {
  width: 100%;
  height: 100%;
  --hexColor: v-bind(hexColor);
  --rgbaColor: v-bind(rgbaColor);

  .picker-card {
    margin-top: 20px;
    width: 100%;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    &--item {
      margin:0 10px 20px;
      padding: 10px;
      cursor: pointer;
      .picker-card--item_tag {
        margin: 10px auto 0;
        width: 50px;
        height: 50px;
        border-radius: 10px;
        position: relative;
        overflow: hidden;
        box-shadow: var(--el-box-shadow-lighter);
        background-color: var(--hexColor);
        &.rgba {
          background-color: var(--rgbaColor);
        }
      }
    }
  }

  .picker-btn {
    margin: 0 auto;
    width: 130px;
    height: 40px;
    font-size: 12px;
    color: #fff;
    background: #409EFF;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
}
</style>
